package controller

import (
	"context"
	"github.com/olivere/elastic/v7"
	"luiz/crawler/engine"
	"luiz/crawler/fronted/model"
	"luiz/crawler/fronted/view"
	"net/http"
	"reflect"
	"strconv"
	"strings"
)

type SearchResultHandler struct {
	View   view.SearchResultView
	Client *elastic.Client
}

func (s SearchResultHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	q := strings.TrimSpace(request.FormValue("q"))
	from, err := strconv.Atoi(request.FormValue("from"))
	if err != nil {
		from = 0
	}
	page, err := s.getSearchResult(q, from)
	if err != nil {
		http.Error(writer, err.Error(), http.StatusBadRequest)
	}
	err = s.View.Render(writer, page)
	if err != nil {
		http.Error(writer, err.Error(), http.StatusBadRequest)
	}
}

func CreateSearchResultHandler(tempalte string) SearchResultHandler {
	client, err := elastic.NewClient(elastic.SetURL("http://124.71.171.6:9200/"))
	if err != nil {
		panic(err)
	}
	return SearchResultHandler{
		view.CreateView(tempalte), client,
	}
}
func (h SearchResultHandler) getSearchResult(q string, from int) (model.SearchResult, error) {
	var result model.SearchResult
	result.Query = q
	do, err := h.Client.Search("ziroo").Query(elastic.NewQueryStringQuery(q)).From(from).Do(context.Background())
	if err != nil {
		return result, err
	}
	result.Hits = do.TotalHits()
	result.Start = from
	result.Items = do.Each(reflect.TypeOf(engine.Item{}))
	result.PrevFrom = result.Start - len(result.Items)
	result.NextFrom = result.Start + len(result.Items)
	return result, err
}
